import { Client } from "../Network/Socket/Client";
import { ClientMessage } from "../Network/Socket/ClientMessage";
import { StoreManager } from "./StoreManager";
import { AdvanceClient } from "../Network/Socket/AdvanceClient";

export class ClientManager
{
    // private static clients:Array<Client> = []; 
    private static clients:{[key:string]:Client} = {}; 
    public static SwapClient(client1:Client,client2:Client):void
    {
        var name1:string = client1.clientName;
        client1.clientName = client2.clientName;
        client2.clientName = name1;

        this.clients[client1.clientName] = client1;
        this.clients[client2.clientName] = client2;
    }
    public static IsActiveClient(clientName:string):boolean
    {
        let client = this.clients[clientName];
        if(client)return client.isConnected;
        return false;
    }
    /**
     * 向指定的Client发送消息
     */		
    public static SendMessage(clientName:string,data:any,action:number,RTOTarget?:any,RTOCallBack?:Function,...RTOPacketIDs):void
    {
        if(data==null)return;
        //data.TimeStamp = new Date().getTime();
        var client:Client = this.GetClientByName(clientName);
        if(client!=null)
        {
            if(client.isConnected)
            {
                var msg:ClientMessage = ClientMessage.Get(action,data,true);
                client.sendMessage(msg);
            }else console.log("[ClientManager] "+clientName," Socket 未连接，无法向服务器发送数据!!!");
        }
    }
    /**
     * 通过ClientName获取到Client实例
     */		
    public static GetClientByName(clientName:string):Client
    {
        let client = this.clients[clientName];
        if(client==null)client = this.GetNewClient(clientName);
        return client;
    }
    /**
     * 关闭Client
     */		
    public static DisposeClients(...clientNames):void
    {
        for (let i = 0; i < clientNames.length; i++) 
        {
            let client:Client = this.clients[clientNames[i]];
            if(client==null)continue;
            client.dispose();
            delete this.clients[clientNames[i]];
            
        }
    }
    private static GetNewClient(clientName:string,ip:string=null,port:number=0):Client
    {
        var client:Client = StoreManager.New(Client);
        if(ip!=null&&port!=0)client.connect(ip,port,"");
        client.clientName = clientName;
        this.clients[clientName] = client;
        return client;
    }
}